<?php

namespace common\helpers;

use mdm\admin\components\MenuHelper as BaseMenuHelper;

/**
 * 自定义MenuHelper类
 *
 * @author emhome<emhome@163.com>
 * @since 1.0
 */
class MenuHelper extends BaseMenuHelper {

    public static function getAssignedModuleMenu($userId, $root = null, $callback = null, $refresh = false) {
        if ($callback == null) {
            $callback = [static::class, 'format'];
        }
        $menus = parent::getAssignedMenu($userId, $root, $callback, $refresh);
        if (empty($menus)) {
            return [];
        }
        return static::menuTree($menus);
    }

    public static function getAssignedMenu($userId, $root = null, $callback = null, $refresh = false) {
        if ($callback == null) {
            $callback = [static::class, 'format'];
        }

        $menus = parent::getAssignedMenu($userId, $root, $callback, $refresh);

        if (empty($menus)) {
            return [];
        }
        $authMenus = [];
        foreach ($menus as $menu) {
            if (empty($menu)) {
                continue;
            }
            if (isset($menu['items'])) {
                unset($menu['items']);
            }
            $authMenus[] = $menu;
        }
        return $authMenus;
    }

    public static function format($menu) {
        $route = rtrim($menu['route'], '/*');
        $item = [
            'label' => $menu['name'],
            'icon' => $menu['icon'],
            'url' => MenuHelper::parseRoute($route),
            'route' => $route,
            'visibled' => $menu['visibled'] ? true : false,
        ];
        if (!empty($menu['children'])) {
            $item['items'] = $menu['children'];
        }
        return $item;
    }

    public static function menuTree($menus) {
        $authMenus = [];
        foreach ($menus as $menu) {
            if (empty($menu)) {
                continue;
            }
            if (isset($menu['items'])) {
                $items = static::menuTree($menu['items']);
                if (count($items) == 1) {
                    $menu = $items[0];
                } else {
                    $menu['items'] = $items;
                }
            }
            $authMenus[] = $menu;
        }
        return $authMenus;
    }

}
